/**
 * This file is part of magnolia-module-bespin.
 * 
 * magnolia-module-bespin is free software: you
 * can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * 
 * magnolia-module-bespin is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU General Public
 * License for more details.
 * 
 * You should have received a copy of the GNU General
 * Public License along with magnolia-module-bespin.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

package com.nrgedge.magnolia.module.ace;

import info.magnolia.cms.core.Content;
import info.magnolia.cms.gui.dialog.DialogBox;
import info.magnolia.cms.gui.misc.CssConstants;

import java.io.IOException;
import java.io.Writer;

import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;

/**
 * Based off of info.magnolia.cms.gui.dialog.DialogEditCode
 * 
 * @author brian.bowman@nrg-edge.com
 * @author adam.galloway@nrg-edge.com
 */
public class DialogEditCodeAce extends DialogBox {
	/**
	 * @see info.magnolia.cms.gui.dialog.DialogControl#drawHtml(Writer)
	 */
	@SuppressWarnings("deprecation")
	public void drawHtml(Writer out) throws IOException {
		
		AceEdit control = new AceEdit(this.getName(), this.getValue());
		
		control.setType(getConfigValue("type", PropertyType.TYPENAME_STRING));
		
		if (this.getConfigValue("saveInfo").equals("false")) {
			control.setSaveInfo(false);
		}
		
		control.setCssClass(CssConstants.CSSCLASS_EDIT + " editor ");
		
		out.write("<script type=\"text/javascript\" src=\"" + getRequest().getContextPath() + "/.resources/ace-editor/src-min-noconflict/ace.js\"></script>");		
		
		out.write(control.getHtml());
		
		out.write("\n<script>\n");
		
		String mode = "ftl";
		String fileName = getStorageNode().getName() + ".ftl";
		
		try {
			if (getStorageNode().hasContent("MetaData")) {
				Content metaData = getStorageNode().getContent("MetaData");
				String template = metaData.getNodeData("mgnl:template").getString();
				
				if ("resources:processedCss".equals(template)) {
					mode = "css";
					out.write("editor.session.setUseWorker(false);");
				} else if ("resources:css".equals(template)) {
					mode = "css";
					fileName = getStorageNode().getName() + ".css";
				} else if ("resources:processedJs".equals(template)) {
					mode = "javascript";
					out.write("editor.session.setUseWorker(false);");
				} else if ("resources:js".equals(template)) {
					mode = "javascript";
					fileName = getStorageNode().getName() + ".js";
				}
			}
		} catch (RepositoryException e) {
			e.printStackTrace();
		}
		
		out.write("editor.getSession().setMode(\"ace/mode/" + mode + "\");\n");
		
		out.write("jQuery(function(){");
		out.write("jQuery('div.mgnlDialogTabsetSaveBar').parent().append('<a href=\"#\" id=\"editor-save\" style=\"position:absolute;bottom:13px;left:10px;\" download=\"" + fileName + "\"><button type=\"button\">Save File</button></a>');");
		
		out.write("jQuery('#editor-save').click(function(){");
		out.write("   jQuery(this).attr('href', 'data:application/octet-stream;base64,' + btoa(editor.getValue()));");
		out.write("   return true;") ;
		out.write("});");
		
		out.write("});");

		
		out.write("MgnlDHTMLUtil.addOnLoad(function(){\n");
		out.write("    var b = document.getElementById('mgnlSaveButton');\n");
		out.write("    var existingOnClick = b.onclick;\n");
		out.write("    b.onclick=function(){\n");
		out.write("        document.getElementById('cp_hidden_" + getName() + "').value = editor.getValue();\n");
		out.write("        existingOnClick.apply(this);\n");
		out.write("    }\n});\n");
		out.write("</script>\n");
		
		out.write("<input type=\"hidden\" name=\"");
		out.write(getName());
		out.write("\" id=\"cp_hidden_" + getName() + "\" />\n");

		this.drawHtmlPost(out);
	}
}